package com.mvc.framework.service;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.mvc.framework.config.ProjectConfig;
import com.mvc.framework.model.Auditable;

@Service
public class HistoryRecordManager extends BaseService<Object, Serializable> {
	private static final String RESULT = "RESULT";

	public int deleteHistoryRecord(Class entityClass,Date endDate){
		if(null==endDate){
			endDate = new Date();
		}
		int result = 0;
		if(Auditable.class.isAssignableFrom(entityClass)){
			String hql = "DELETE FROM " + entityClass.getName() + " where recStatus= " + Auditable.REC_STATUS_INVALID
							+ " AND updatedOn >?";
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			Query query = session.createQuery(hql).setParameter(0, endDate);
			result = query.executeUpdate();
		}
		return result;
	}


	public void deleteAllHistoryRecord(Date endDate){
		if(null==endDate){
			endDate = new Date();
		}
		List allModel = ProjectConfig.getAllModel();
		for(Object model : allModel){
			deleteHistoryRecord(model.getClass(),endDate);
		}
	}

	public void deleteHistoryRecordByTableName(String talbeName,Date endDate){
		List allModel = ProjectConfig.getAllModel();
		for(Object model : allModel){
			Entity entityClass = model.getClass().getAnnotation(Entity.class);
			if(talbeName.equalsIgnoreCase(entityClass.name())){
				deleteHistoryRecord(model.getClass(),endDate);
				break;
			}
		}
	}

	public Map<String,Long> getAllModelHistoryRecordCount(){
		List allModel = ProjectConfig.getAllModel();
		Map<String,Long> result = new HashMap<String, Long>();
		Date endDate = new Date();
		for(Object model : allModel){
			if(model instanceof Auditable){
				Entity entity = model.getClass().getAnnotation(Entity.class);
				result.put(entity.name(),getHistoryRecordCount(entity.name(),endDate));
			}
		}
		return result;
	}

	public long getHistoryRecordCount(String tableName,Date endDate){
		if(null==endDate){
			endDate = new Date();
		}
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		String sql = "SELECT COUNT(*) AS " + RESULT + " FROM " + tableName + " where rec_Status= " + Auditable.REC_STATUS_INVALID
						+ " AND updated_On >?";
		SQLQuery query = session.createSQLQuery(sql);
		query.setParameter(0, endDate);
		query.addScalar(RESULT, new org.hibernate.type.IntegerType());
		List children = query.list();
		long result = ((Number) children.iterator().next()).longValue();
		session.close();
		return result;
	}

}
